import type { OptionTypes, ResponseData } from '@/utils/typings.d';
import { SUCCESS_CODE } from '@/utils/typings.d';
import { request } from 'umi';
import type {
  CreateSystemUserType,
  SystemUserTableListItem,
  UpdateAuthType,
  UpdateSystemUserType,
} from './typings.d';

export async function queryUserList(
  params: any,
  sort: any,
): Promise<{
  success: boolean;
  total: number;
  data: SystemUserTableListItem[];
}> {
  const res = await request('/api/system-user/v1.0.0/list', {
    method: 'GET',
    params: {
      data: params,
      sort,
    },
  });
  if (res?.code !== SUCCESS_CODE || !res.data) return { success: false, total: 0, data: [] };
  return { success: true, total: res.data.total, data: res.data.data };
}

// 获取权限
export async function getAuthById(id: string) {
  const res: ResponseData<USER.AuthType> = await request('/api/system-user/v1.0.0/auth', {
    params: {
      id,
    },
  });
  const { code, data, message } = res;
  if (code === SUCCESS_CODE) return { hasAuth: true, data };
  return { hasAuth: false, message, data };
}

//   /api/auth/v2.0.0/auth/{id}
// 更改权限
export async function updateAuthById(id: string, newData: UpdateAuthType) {
  const res = await request(`/api/system-user/v1.0.0/auth/${id}`, {
    method: 'PUT',
    data: newData,
  });
  if (res?.code === 0) return { success: true, message: '更新成功' };
  return { success: false, message: res?.message || '更新失败' };
}

export async function createUser(params: CreateSystemUserType) {
  const res = await request('/api/system-user/v1.0.0/systemUser', {
    method: 'POST',
    data: params,
  });
  if (res?.code === SUCCESS_CODE) return { data: res.data, success: true, message: '添加成功' };
  return { data: res?.data, success: false, message: res?.message || '添加失败' };
}

export async function updateUser(id: string, newInfo: UpdateSystemUserType) {
  if (!id || !newInfo || Object.keys(newInfo).length === 0) {
    return { success: false, message: '更新失败，请填入需要更新的信息' };
  }
  const res = await request(`/api/system-user/v1.0.0/systemUser/${id}`, {
    method: 'PUT',
    data: newInfo,
  });
  if (res?.code === SUCCESS_CODE) return { success: true, data: res.data, message: '更新成功' };
  return { success: false, data: res?.data, message: res?.message || '更新失败' };
}

export async function queryCompanies(name: string, options = true): Promise<OptionTypes[]> {
  const res = await request('/api/system-user/v1.0.0/companies', {
    params: { name },
  });
  if (res?.code === SUCCESS_CODE) {
    return options ? res.data : res.data.filter((item: OptionTypes) => item.value !== 'admin');
  }
  return [];
}

export async function removeUser(id: string) {
  const res = await request(`/api/system-user/v1.0.0/systemUser/${id}`, {
    method: 'DELETE',
  });
  if (res?.code === SUCCESS_CODE) return { success: true, message: '删除成功' };
  return { success: false, message: res?.message || '删除失败' };
}
